package com.leo.persistence.config;

import com.leo.persistence.io.Resources;
import com.leo.persistence.pojo.Configuration;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * sqlMapConfig.xml解析
 */
public class XmlConfigBuilder {

    private Configuration configuration;

    public XmlConfigBuilder() {
        this.configuration = new Configuration();
    }

    // dom4j解析
    public Configuration parseConfig(InputStream in){

        try {

            Document document = new SAXReader().read(in);
            // <configuration> 根节点
            Element rootElement = document.getRootElement();

            Properties properties = new Properties();

            // XPATH全局获取 property节点集合
            List<Element> list = rootElement.selectNodes("//property");
            for (Element element : list) {
                String name = element.attributeValue("name");
                String value = element.attributeValue("value");
                properties.setProperty(name, value);
            }

            // 使用c3p0连接池，解决session复用
            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setDriverClass(properties.getProperty("driverClass"));
            ds.setJdbcUrl(properties.getProperty("jdbcUrl"));
            ds.setUser(properties.getProperty("username"));
            ds.setPassword(properties.getProperty("password"));

            configuration.setDataSource(ds);

            //mapper.xml解析: 拿到路径--字节输入流---dom4j进行解析
            List<Element> mapperList = rootElement.selectNodes("//mapper");
            for (Element element : mapperList) {
                String mapperPath = element.attributeValue("resource");
                InputStream resourceAsSteam = Resources.getResourceAsStream(mapperPath);

                // 传递configuration，因为mapper属性需要设置进去
                XmlMapperBuilder xmlMapperBuilder = new XmlMapperBuilder(configuration);
                xmlMapperBuilder.parse(resourceAsSteam);

            }

        } catch (DocumentException | PropertyVetoException e) {
            e.printStackTrace();
        }
        return configuration;
    }
}
